<?php

defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'get';
$return=array();
$return['account']=$_SESSION['account'];
$return['extradata']=array();
$setting=uni_setting('register');
$setting['login_type']=intval($setting['login_type']);
$_SESSION['isauth_base']=0;
set_html('title','登录会员');
if(!$_SESSION['wechat_id']){
	$wechat=pdo_get('core_account_wechat',array('uniacid'=>$_SESSION['uniacid'],'isdefault'=>1),array('id','appid','appsecret','type','oldid','is_open'));
	if(!$wechat){
		$wechat=pdo_get('core_account_wechat',array('uniacid'=>$_SESSION['uniacid']),array('id','appid','appsecret','type','oldid','is_open'));
	}
	$_SESSION['wechat_id']=$wechat['id'];
}
if($_RQ['op']=='get'){
	if($_RQ['forward']){
		$url = base64_decode($_RQ['forward']);
		$_SESSION['forward_url']=base64_decode($_RQ['forward']);
	}elseif($_SESSION['forward_url']){
		$url = $_SESSION['forward_url'];
	}else{
		$url = 'core/member.home/';
	}
	if($_SESSION['uid']){
		$member=pdo_get('core_members',array('id'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']),array('id'));
		if(empty($member)){
			model('core/member')->logout();
		}else{
			exi('','',$url);
		}
	}
	$return['item']=array();
	$return['title']='登录';
	$item=array();
	$item['show_type']=$setting['login_type']==2?true:false;
	$item['login_type']=$setting['login_type'];
	if($_RQ['forward']){
		$item['forward']=base64_decode($_RQ['forward']);
	}
	$item['openid']=$_SESSION['openid'];
	$return['item']=$item;
	if($_SESSION['os']=='windows'){
		$return['session_id']=session_id();
	}
	$return['mobile_code']=$_AR['system']['mobile_code']?true:false;
	if($_SESSION['container']!='wechat' && $_SESSION['container']!='wxapp' && $_SESSION['container']){
		$return['openlogin']=$_SESSION['container'].'_login';
		$os=get_os($_SESSION['container']);
		$return['opentitle']=get_ostitle()[$os];
		$return['os_cont']=$_SESSION['container'].'~~'.$_SESSION['os'];
	}
	//$return['opentitle']=$_SESSION['openid'];
	exi($return);
}
if($_RQ['op']=='login'){
	//登陆
	$post=get_postdata();	
	$login_type=intval($post['login_type']);
	$login_type=$login_type==2?0:$login_type;
	if($login_type==1){
		//手机验证码登陆
		if(!check_sms_code($post['smscode'])){
			exi('手机验证码错误！','error');
		}
		$member=pdo_get('core_members',array('mobile'=>trim($post['mobile']),'uniacid'=>$_SESSION['uniacid']),array('id','onemid'));
		$uid=$member['onemid']?:$member['id'];
		if(!$uid){
			exi('用户不存在，请先注册!'.$post['mobile'],'error');
		}
	}else{
		//账号密码登陆
		if(!$post['username']){
			exi('请输入账号！','error');
		}
		if(!$post['password']){
			exi('请输入密码！','error');
		}
		$user=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'username'=>$post['username']),array('id','onemid','salt','password'));
		if(empty($user)){
			exi('用户不存在，请先注册!','error');
		}
		if(!check_password($post['password'],$user['salt'],$user['password'])){
			exi('账号或密码错误!','error');
		}
		$uid=$user['onemid']?:$user['id'];
	}
	model('core/member')->login($uid);
	if($post['forward']){
		$forward_url=custom_url($post['forward'],true);
		
	}elseif($_SESSION['forward_url']){
		$forward_url=$_SESSION['forward_url'];
	}else{
		$forward_url='goback';
	}
	exi('登陆成功！','success',$forward_url);
}
if($_RQ['op']=='wechat_login'){
	//微信一键登陆
	$post=get_postdata();	
	if($post['openid'] && !$_SESSION['openid']){
		$openid=cfc('tools')->base64_decode($post['openid'],BASE64_KEY);
		//写入OPENID缓存
		$_SESSION['openid']=$openid;
	}else{
		$openid=$_SESSION['openid'];
	}	
	if(!$openid){
		exi('获取用户openid失败，无法微信一键登陆（联系管理员配置好公众号）！','error');
	}
	$mid=pdo_getcolumn('core_fans',array('uniacid'=>$_SESSION['uniacid'],'openid'=>$openid,'wxgid'=>$_SESSION['wechat_id']),'mid');
	if(!$mid){
		$mid=model('core/member')->register();
	}
	model('core/member')->login($mid);	
	if($post['forward']){
		$forward_url=custom_url($post['forward'],true);
	}elseif($_SESSION['forward_url']){
		$forward_url=custom_url($_SESSION['forward_url'],true);
	}else{
		$forward_url=custom_url('/member.home/',true);
	}
	exi('登陆成功！','success',$forward_url);
}
if($_RQ['op']=='wxapp_login'){
	//四合一小程序登陆
	if(!$_SESSION['openid']){
		exi('获取用户openid失败，无法一键登陆（联系管理员配置好小程序）！','error');
	}
	$post=get_postdata();
	$params=array('openid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid']);
	if($_SESSION['container']=='ttapp'){
		$params['ttgid']=$_SESSION['appgid'];
	}elseif($_SESSION['container']=='aliapp'){
		$params['aligid']=$_SESSION['appgid'];
	}elseif($_SESSION['container']=='baiduapp'){
		$params['baidugid']=$_SESSION['appgid'];
	}else{
		$params['wxgid']=$_SESSION['appgid'];
	}
	$uid=pdo_getcolumn('core_fans',$params,'mid');
	if($uid){
		$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),array('id','nickname','avatar','sex'));
		$mid=$member['id'];
	}
	if($post['userInfo']){
		//获取到用户信息
		$fansdata=array(
			'nickname'=>model('core/tools')->upnickname($post['userInfo']['nickName']),
			'avatar'=>$post['userInfo']['avatarUrl']?:$post['userInfo']['avatar'],
			'pcd'=>$post['userInfo']['country'].$post['userInfo']['province'].$post['userInfo']['city'],
			'sex'=>$post['userInfo']['gender'],
		);
		pdo_update('core_fans',$fansdata,$params);
		if(!$uid || !$mid){
			//尚未注册，直接注册
			do{
				$username='wxapp_'.random(10);
			}while(pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'username'=>$username),'id'));
			$new_member=array(
				'uniacid'=>$_SESSION['uniacid'],
				'from_os'=>1,
				'createtime'=>TIMESTAMP,
				'unionid'=>$_SESSION['unionid'],
				'nickname'=>$fansdata['nickname'],
				'avatar'=>$fansdata['avatar'],
				'sex'=>$fansdata['sex'],
				'username'=>$username,
			);
			$uid=model('core/member')->register($new_member);
			pdo_update('core_fans',array('mid'=>$uid),$params);
		}else{
			$member_update=array();
			if(!$member['nickname']){
					$member_update['nickname']=$fansdata['nickname'];
			}
			if(!$member['avatar']){
					$member_update['avatar']=$fansdata['avatar'];
			}
			if(!$member['sex']){
					$member_update['sex']=$fansdata['sex'];
			}
			if($member_update){
					model('core/member')->member_update($uid,$member_update);
			}
		}
		if($_RQ['return_info']){
			exi($fansdata);
		}
		model('core/member')->login($uid);
	}else{
		//解密获取手机号		
		require ROOT_D.'/core/library/wxapp_decode/wxBizDataCrypt.php';
		if($_SESSION['container']=='ttapp'){
			$appidname='tt_appid';
		}elseif($_SESSION['container']=='aliapp'){
			$appidname='ali_appid';
		}elseif($_SESSION['container']=='baiduapp'){
			$appidname='baidu_appid';
		}else{
			$appidname='appid';
		}
		$appid=pdo_getcolumn('core_account_wxapp',array('id'=>$_SESSION['appgid'],'uniacid'=>$_SESSION['uniacid']),$appidname);
		if(!$appid || !$_SESSION['session_key']){
			exi('小程序参数错误！无法获取粉丝信息！','error');
		}
		$pc = new WXBizDataCrypt($appid, $_SESSION['session_key']);
		$errCode = $pc->decryptData($post['encryptedData'], $post['iv'],$data);
		if ($errCode) {
			exi($errCode ,'error');
		}
		$data=json_decode($data,true);
		$mobile=$data['purePhoneNumber'];//获取没有区的手机号
		if(!$uid){
			//尚未注册，直接注册			
			$new_member=array(
				'mobile'=>$mobile,
				'realmobile'=>$mobile
			);
			$uid=model('core/member')->register($new_member);
			model('core/member')->login($uid);
			pdo_update('core_fans',array('mid'=>$uid),$params);
		}else{
			$oldmobile=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),'mobile');
			if($mobile!=$oldmobile){
				pdo_update('core_members',array('mobile'=>$mobile,'realmobile'=>$mobile),array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid));
				model('core/member')->merge_memberdata($mobile,'',$oldmobile);
			}
		}
		if($_RQ['return_mobile']){
			$res=array('uid'=>$uid,'mobile'=>$mobile);
			exi($res);
		}
	}
	if($_SESSION['forward_url']){
		exi('登陆成功!','',$_SESSION['forward_url']);
	}else{
		exi('登陆成功!','','goback');
	}
}
if($_RQ['op']=='open_login'){
	if(!$_AR['system']['wechat_login']){
		exi('系统暂不支持微信登陆！','error','./index.php');
	}
	if($_RQ['step']=='local_back'){
		if(!$_RQ['code']){
			exi('授权登陆失败！','error','get');
		}
		$setting=core_setting('system');
		$api="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$setting['wechat_login_appid']}&secret={$setting['wechat_login_appsecret']}&code={$_RQ['code']}&grant_type=authorization_code";
		$result=file_get_contents($api);
		$result=json_decode($result,true);
		if($result['errcode']){
			exi($result['errmsg'],'error','get');
		}
		//获取openid后转至正常处理流程
		$_RQ['openid']=$result['openid'];
		$_RQ['step']='cloud_back';
	}
	if($_RQ['step']=='cloud_back'){
		if($_RQ['openid']){
			//获得openid，为用户登陆
			$openid=trim($_RQ['openid']);
			$_SESSION['openid']=$openid;
			$params=array('openid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid']);
			$uid=pdo_getcolumn('core_fans',$params,'mid');
			if($uid){
				$mid=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),'id');
			}
			//获取到用户信息
			$fansdata=array(
				'nickname'=>model('core/tools')->upnickname($result['userInfo']['nickName']),
				'avatar'=>$result['userInfo']['avatarUrl'],
				'pcd'=>$result['userInfo']['country'].$result['userInfo']['province'].$result['userInfo']['city'],
				'sex'=>$result['userInfo']['gender'],
			);
			pdo_update('core_fans',$fansdata,$params);
			if(!$uid || !$mid){
				//尚未注册，直接注册
				do{
					$username='wxapp_'.random(10);
				}while(pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'username'=>$username),'id'));
				$new_member=array(
					'uniacid'=>$_SESSION['uniacid'],
					'from_os'=>1,
					'createtime'=>TIMESTAMP,
					'unionid'=>$_SESSION['unionid'],
					'nickname'=>$fansdata['nickname'],
					'avatar'=>$fansdata['avatar'],
					'sex'=>$fansdata['sex'],
					'username'=>$username,
				);
				$uid=model('core/member')->register($new_member);
				pdo_update('core_fans',array('mid'=>$uid),$params);
			}else{
				unset($fansdata['pcd']);
				pdo_update('core_members',$fansdata,array('id'=>$uid));
			}
			if($_RQ['return_info']){
				exi($fansdata);
			}
			model('core/member')->login($uid);
			$message='授权登陆成功！';
		}else{
			$message='授权登陆失败！';
		}
		//跳转首页
		$_SESSION['access']=array();
		exi($message,'','./index.php');
	}
	//微信授权登陆，先检查是否配置好微信授权登陆参数，如尚未配置，则通过云平台接口完成登陆，否则通过本地接口完成登陆
	$setting=core_setting('system');
	if($setting['wechat_login_appid'] && $setting['wechat_login_appsecret']){
		$back_url=urlencode(SITEROOT.'manage/index.php?plugin=core&action=user.login&op=open_login&step=local_back');
		$url="https://open.weixin.qq.com/connect/qrconnect?appid={$setting['wechat_login_appid']}&redirect_uri={$back_url}&response_type=code&scope=snsapi_login&state=state#wechat_redirect";
	}else{
		$back_url=SITEROOT.'manage/index.php?plugin=core&action=user.login&op=open_login&step=cloud_back';
		$url=cloud_request('cloud.login.wechat',array('back_url'=>$back_url));
	}
	exi('','',$url);
}
if($_RQ['op']=='qq_login'){
	if(!$_AR['system']['qq_login']){
		exi('系统暂不支持QQ登陆！','error','./index.php');
	}
	if($_RQ['step']=='local_back'){
		if(!$_RQ['code']){
			exi('授权登陆失败！','error','get');
		}
		$setting=core_setting('system');
		$back_url=urlencode(SITEROOT.'custom/index.php?plugin=core&action=member.login&op=qq_login&step=local_back');
		$url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={$setting['qq_login_appid']}&client_secret={$setting['qq_login_appsecret']}&code={$_RQ['code']}&redirect_uri={$back_url}";
		$res=file_get_contents($url);
		$res=explode('&',$res);
		$result=array();
		foreach($res as $row){
			$row=explode('=',$row);
			$result[$row['0']]=$row['1'];
		}
		$url='https://graph.qq.com/oauth2.0/me?access_token='.$result['access_token'];
		$res=file_get_contents($url);
		$res=substr($res,9,-3);
		$res=json_decode($res,true);
		//获取openid后转至正常处理流程
		$_RQ['openid']=$res['openid'];
		$_RQ['step']='cloud_back';
	}
	if($_RQ['step']=='cloud_back'){
		if($_RQ['openid']){
			//获得openid，为用户登陆
			$openid=trim($_RQ['openid']);
			$_SESSION['openid']=$openid;
			$params=array('openid_qq'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid']);
			$uid=pdo_getcolumn('core_fans',$params,'mid');
			if($uid){
				$mid=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$uid),'id');
				//获取到用户信息
				$fansdata=array(
					'nickname'=>model('core/tools')->upnickname($result['userInfo']['nickName']),
					'avatar'=>$result['userInfo']['avatarUrl'],
					'pcd'=>$result['userInfo']['country'].$result['userInfo']['province'].$result['userInfo']['city'],
					'sex'=>$result['userInfo']['gender'],
				);
				pdo_update('core_fans',$fansdata,$params);
			}else{
				$fansdata=array(
					'uniacid'=>$_SESSION['uniacid'],
					'openid_qq'=>$_SESSION['openid'],
					'type'=>3,
					'createtime' => TIMESTAMP,
				);
				if($result['unionid']){
					$fansdata['unionid']=$result['unionid'];
				}
				pdo_insert('core_fans',$fansdata);
			}
			
			if(!$uid || !$mid){
				//尚未注册，直接注册
				do{
					$username='qq_'.random(10);
				}while(pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'username'=>$username),'id'));
				$new_member=array(
					'uniacid'=>$_SESSION['uniacid'],
					'from_os'=>3,
					'createtime'=>TIMESTAMP,
					'unionid'=>$_SESSION['unionid'],
					'nickname'=>$fansdata['nickname'],
					'avatar'=>$fansdata['avatar'],
					'sex'=>$fansdata['sex'],
					'username'=>$username,
				);
				$uid=model('core/member')->register($new_member);
				pdo_update('core_fans',array('mid'=>$uid),$params);
			}else{
				unset($fansdata['pcd']);
				//pdo_update('core_members',$fansdata,array('id'=>$uid));
			}
			if($_RQ['return_info']){
				exi($fansdata);
			}
			model('core/member')->login($uid);
			exi('授权登陆成功！');
		}else{
			$_SESSION['access']=array();
			exi('授权登录失败！');
		}
		
	}
	//QQ授权登陆
	$setting=core_setting('system');
	if($setting['qq_login_appid'] && $setting['qq_login_appsecret']){
		$back_url=urlencode(SITEROOT.'manage/index.php?plugin=core&action=user.login&op=qq_login&step=local_back');
		$url="https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={$setting['qq_login_appid']}&redirect_uri={$back_url}&state=state";
	}else{
		$back_url=SITEROOT.'manage/index.php?plugin=core&action=user.login&op=qq_login&step=cloud_back';
		$url=cloud_request('cloud.login.qq',array('back_url'=>$back_url));
	}
	exi('','',$url);
}
//微信授权登陆
if($_RQ['op']=='sq_login'){
	if(!$_SESSION['openid']){
		exi('暂不支持微信一键登录，联系管理员配置好公众号！','error');
	}
	$openid=model('core/tools')->base64_encode($_SESSION['openid'],BASE64_KEY);
	model('core/jinyun_socket')->send2uid(array('openid'=>$openid),$_RQ['session_id']);
	if($_SESSION['forward_url']){
		exi('登陆成功！','',$_SESSION['forward_url']);
	}elseif($_RQ['forward_url'] && $_RQ['forward_url']!='null'){
		$forward_url=base64_decode($_RQ['forward_url']);
		exi('登陆成功！','',$forward_url);
	}else{
		exi('登陆成功！','','core/home.welcome/');
	}
}
if($_RQ['op']=='wxauth_check'){
	$params=array('openid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid']);
	$return['fans']=pdo_get('core_fans',$params,array('nickname','avatar','sex'));
	$return['session_id']=$_RQ['session_id'];
	$return['forward_url']=$_RQ['forward']?:$_RQ['forward_url'];
	exi($return);
}
?>